const express = require("express");
const multer = require("multer");
const mysql = require("mysql");
// 创建
const app = express();
// 引入jwt
const jwt = require("jsonwebtoken");
// 引入jwt解析中间件
const { expressjwt } = require("express-jwt");
// jwt配置信息
const config = {
  // 加密和解密 token 的密钥
  jwtSecretKey: "jay No1. ^_^",
  // token 有效期
  expiresIn: "80m",
};
const cors = require("cors");
// 使用cors解决跨域问题
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 使用jwt解析中间件
// app.use(
//   expressjwt({
//     secret: config.jwtSecretKey, //加密时使用的密钥
//     algorithms: ["HS256"],
//   }).unless({
//     path: ["/login","/upload"]
//   })
// );
app.use((err, req, res, next) => {
  if (err.name === "UnauthorizedError") {
    return res.send({ code: err.status, msg: err.inner.message });
  }
  next();
});
// 创建数据库连接
const db = mysql.createPool({
  // 数据库IP地址
  host: "127.0.0.1",
  // 数据库用户名
  user: "root",
  // 数据库密码
  password: "root",
  // 数据库
  database: "node",
});
const multerConfig = multer({
  storage: multer.diskStorage({
    destination: "public",
    filename(req, file, cb) {
      //   console.log(file);
      const fileFormat = file.originalname.split(".");
      cb(null, Date.now() + "." + fileFormat.at(-1));
    },
  }),
  limits: {
    // 限制文件大小不超过5mb
    fileSize: 1024 * 1024 * 5,
  },
});
app.use("/img", express.static("public"));
// 图片上传
app.post("/upload", multerConfig.single("file"), (req, res) => {
  res.send({
    code: 0,
    msg: "成功",
    data: req.file.filename,
  });
});
// 测试
app.get("/user", (req, res) => {
  db.query("select * from user", (err, result) => {
    if (err) {
      return res.send({ code: 999, msg: err, data: null });
    }
    res.send({ code: 0, msg: "查询成功", data: result });
  });
});
app.post("/user", (req, res) => {
  console.log(req.body);
  db.query(
    `insert into user(id,name,password) value(${req.body.id},"${req.body.name}","${req.body.password}")`,
    (err, result) => {
      if (err) return res.send({ code: 999, msg: err });
      if (result.affectedRows > 0) {
        return res.send({ code: 0, msg: "添加成功" });
      } else {
        return res.send({ code: 5000, msg: "添加失败" });
      }
    }
  );
});
app.delete("/user", (req, res) => {
  db.query(`delete from user where id=${req.body.id}`, (err, result) => {
    if (err) return res.send({ code: 888, msg: err });
    if (result.affectedRows > 0) {
      return res.send({ code: 0, msg: "删除成功" });
    } else {
      return res.send({ code: 5000, msg: "删除失败" });
    }
  });
});
app.put("/user", (req, res) => {
  db.query(
    `update user set ? where id=${req.body.id}`,
    { name: req.body.name, password: req.body.password },
    (err, result) => {
      if (err) return res.send({ code: 888, msg: err });
      if (result.affectedRows > 0) {
        return res.send({ code: 0, msg: "删除成功" });
      } else {
        return res.send({ code: 5000, msg: "删除失败" });
      }
    }
  );
});
app.post("/login", (req, res) => {
  db.query(
    `select * from user where name=? and password=?`,
    [req.body.name, req.body.password],
    (err, result) => {
      if (err) return res.status(500).send({ code: 999, msg: err.message });
      //   console.log(result.length);
      if (result.length === 0) {
        //   失败
        res.send({ code: 5000, msg: "用户名或者密码错误" });
      } else {
        // 成功
        // res.send({ code: 5000, msg: "登录成功" });
        const user = {
          ...result[0],
          password: "",
        };
        const tokenStr = jwt.sign(user, config.jwtSecretKey, {
          expiresIn: config.expiresIn,
        });
        res.send({
          code: 0,
          msg: "登陆成功",
          data: {
            ...user,
            token: "Bearer" + tokenStr,
          },
        });
      }
    }
  );
  //   console.log(tokenStr); //eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiYWRtaW4iLCJwYXNzd29yZCI6IjIyMiIsImlhdCI6MTcyODYyOTQ3OCwiZXhwIjoxNzI4NjMwMDc4fQ.s4_bYnEo7ayeScgOcBXgqvpaHrRksgMzF3KXWzm6jN0
  //   res.send(tokenStr);
});
// 启动
app.listen(3000, () => {
  console.log("项目启动了");
});
